﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace Tilver.Common
{
    /// <summary>
    /// 序列化XML帮助类
    /// </summary>
    public static class XmlSerializerHelper
    {
        /// <summary>
        /// 序列化XML
        /// </summary>
        /// <param name="type"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string Serialize(Type type, object source)
        {
            string ret = null;
            XmlSerializer ser = new XmlSerializer(type);
            using (StringWriter sw = new StringWriter())
            {
                ser.Serialize(sw, source);
                ret = sw.ToString();
            }
            return ret;
        }
        /// <summary>
        /// 反序列化XML
        /// </summary>
        /// <param name="type"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        public static object Deserialize(Type type, string source)
        {
            object ret = null;
            using (StringReader sr = new StringReader(source))
            {
                XmlSerializer ser = new XmlSerializer(type);
                ret = ser.Deserialize(sr);
            }
            return ret;
        }
    }
}
